import { createRequire } from 'module';
import { join } from 'path';

export class NodeIsolatedLoader {
    private readonly require: NodeRequire;
    private loadedModules = new Map<string, any>();

    constructor(basePath: string) {
        this.require = createRequire(join(basePath, 'package.json'));
    }

    load<T>(moduleName: string): T {
        if (this.loadedModules.has(moduleName)) {
            return this.loadedModules.get(moduleName);
        }

        const module = this.require(moduleName);
        this.loadedModules.set(moduleName, module);
        return module;
    }

    clearCache() {
        this.loadedModules.clear();
    }
}